﻿using System;
using System.Runtime.InteropServices;

namespace FileSC.WinAPI
{
    public class FilePicker
    {
        public static string Choose()
        {
            OpenFileName ofn = new OpenFileName();

            ofn.structSize = Marshal.SizeOf(ofn);
            ofn.filter = "所有文件 (*.*)\0*.*\0";
            ofn.file = new string(new char[256]);
            ofn.maxFile = ofn.file.Length;
            ofn.fileTitle = new string(new char[64]);
            ofn.maxFileTitle = ofn.fileTitle.Length;
            //ofn.initialDir = "C:\\"; // Set default directory
            ofn.title = "选择文件";
            ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;

            if (GetOpenFileName(ofn))
            {
                return ofn.file;
            }
            return string.Empty;
        }


        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal class OpenFileName
        {
            internal int structSize = 0;
            internal IntPtr hwndOwner = IntPtr.Zero;
            internal IntPtr hInstance = IntPtr.Zero;
            internal string filter = null;
            internal string customFilter = null;
            internal int maxCustFilter = 0;
            internal int filterIndex = 0;
            internal string file = null;
            internal int maxFile = 0;
            internal string fileTitle = null;
            internal int maxFileTitle = 0;
            internal string initialDir = null;
            internal string title = null;
            internal int flags = 0;
            internal short fileOffset = 0;
            internal short fileExtension = 0;
            internal string defExt = null;
            internal IntPtr custData = IntPtr.Zero;
            internal IntPtr hook = IntPtr.Zero;
            internal string templateName = null;
            internal IntPtr reservedPtr = IntPtr.Zero;
            internal int reservedInt = 0;
            internal int flagsEx = 0;
        }

        [DllImport("Comdlg32.dll", ExactSpelling = true, EntryPoint = "GetOpenFileNameW", CallingConvention = CallingConvention.StdCall, SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Unicode)]
        internal static extern bool GetOpenFileName([In, Out] OpenFileName ofn);

    }
}
